package com.lin.test;

import com.lin.mybatis.dao.UserDao;
import com.lin.mybatis.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author : linwen
 * @date : 下午11:24 2021/10/11
 */
public class 缓存测试 {
    static SqlSessionFactory sqlSessionFactory = null;
    @BeforeClass
    public static void befClass() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void testCache1(){
        // 一级缓存
        /*一级缓存（本地缓存）
        默认开启一级缓存
        在以下四种情况下，缓存会失效
        - sqlsession不是同一个
        - 查询条件不是同一个
        - 在两个查询之间进行了增删改的操作
        - 手动清除了一级缓存  session.clearCache();
        */
        SqlSession session = sqlSessionFactory.openSession();
        UserDao mapper1 = session.getMapper(UserDao.class);
        User user = mapper1.getUserById(3);
        System.out.println(user);
        // 只会发送一次sql
        User user1 = mapper1.getUserById(3);
        System.out.println(user1);
        session.close();

    }

    @Test
    public void testCache2(){
        // 二级缓存
        SqlSession session1 = sqlSessionFactory.openSession();
        UserDao mapper1 = session1.getMapper(UserDao.class);
        User user1 = mapper1.getUserById(3);
        System.out.println(user1);
        // 需要先将session提交才能看到二级缓存
        session1.close();
        SqlSession session2 = sqlSessionFactory.openSession();
        UserDao mapper2 = session2.getMapper(UserDao.class);
        User user2 = mapper2.getUserById(3);
        System.out.println(user2);
        session2.close();
    }

    @Test
    public void test2() {
        // 二级缓存
        SqlSession session1 = sqlSessionFactory.openSession();
        UserDao mapper1 = session1.getMapper(UserDao.class);
        User user1 = mapper1.getUserById(3);
        System.out.println(user1);
        // clearCache 只会清除当前session下的缓存，二级缓存不受影响
        session1.clearCache();
        // 需要先将session提交才能看到二级缓存
        session1.close();
        SqlSession session2 = sqlSessionFactory.openSession();
        UserDao mapper2 = session2.getMapper(UserDao.class);
        User user2 = mapper2.getUserById(3);
        System.out.println(user2);
        session2.close();
    }
}
